<template>
	<!--:title="dataItem.belongDate ? `${dataItem.belongDate} / ${dataItem.scheduleShiftName} / ${dataItem.scheduleGroupName}-替岗` : '暂无'"-->
	<jk-dialog
		v-model="showDialog"
		:title="`${dataItem.id ? '编辑' : '新增'}-人员替岗`"
		width="1100px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		append-to-body
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" :show-message="false">
			<div ref="box1">
				<div class="flex-between-center margin-bottom-4">
					<el-tag effect="plain" class="">
						<div class="el-icon-user item-gap"></div>
						<span>原值班人</span>
					</el-tag>
					<div class="flex-start-center">
						<div class="margin-right-10">
							<span>日期:</span>
							<el-tag size="mini" type="info">{{ ruleForm.belongDate || '无' }}</el-tag>
						</div>
						<div class="margin-right-10">
							<span>班次:</span>
							<el-tag size="mini" type="info">{{ ruleForm.scheduleShiftName ? `${ ruleForm.scheduleShiftName } (${ruleForm.scheduleShiftBeginTime}~${ruleForm.scheduleShiftEndTime})` : '无' }}</el-tag>
						</div>
						<div>
							<span>班组:</span>
							<el-tag size="mini" type="info">{{ ruleForm.scheduleGroupName || '无' }}</el-tag>
						</div>
					</div>
				</div>
				<jk-card class="margin-bottom-10">
					<el-row>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="原值班人">
								<span class="read-only-2">{{ ruleForm.scheduleEmpName || '' }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="上班时间">
								<span class="read-only-2">{{ ruleForm.startDateTime || '' }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="下班时间">
								<span class="read-only-2">{{ ruleForm.endDateTime || '' }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="岗位" prop="postId">
								<el-select v-model="ruleForm.postId" placeholder="岗位" clearable class="width-100-percent" @change="getMachineByPostId">
									<el-option v-for="item in ruleForm.scheduleEmpPostList" :key="item.postId" :label="item.postName" :value="item.postId" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="退岗原因" prop="scheduleEmpExceptionalCaseId">
								<el-select v-model="ruleForm.scheduleEmpExceptionalCaseId" placeholder="退岗原因" clearable class="width-100-percent">
									<el-option v-for="item in causeList" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item class="margin-bottom-10" label="备注">
								<el-input v-model="ruleForm.remark" type="textarea" :rows="1" placeholder="备注" />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item class="margin-bottom-0" label="责任机台">
								<el-checkbox-group v-model="checkArr" size="small" @change="onCheckboxChange">
									<el-checkbox-button
										v-for="(item) in machineList"
										:key="item.machineId"
										:label="item.machineId"
									>{{ item.machineName }}</el-checkbox-button>
								</el-checkbox-group>
								<el-tag v-if="!machineList || !machineList.length" size="medium">无</el-tag>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
			</div>
			<div ref="box2" class="margin-bottom-4 flex-between-center">
				<el-tag effect="plain" class="">
					<div class="el-icon-user-solid item-gap"></div>
					<span>新值班人 ({{ ruleForm.replaceEmpList ? ruleForm.replaceEmpList.length : 0 }}人)</span>
				</el-tag>
				<jk-button icon="el-icon-plus" size="mini" type="primary" :disabled="!ruleForm.postId" @click="onAddBtn(null)"></jk-button>
			</div>
			<jk-table border :data="ruleForm.replaceEmpList || []" :height="dialogTableHeight - 10">
				<vxe-column title="操作" align="center" field="operation" :width="110">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button size="mini" type="datetime" icon="el-icon-plus" class="item-gap" @click="onAddBtn(scope.rowIndex)"></jk-button>
							<jk-button size="mini" type="datetime" icon="el-icon-minus" @click="onDeleteBtn(scope.rowIndex)"></jk-button>
						</div>
					</template>
				</vxe-column>
				<vxe-column title="新值班人" align="left" field="shiftName" :width="140">
					<template slot-scope="scope">
						<remote-search-emp-input
							placeholder="新值班人"
							only-key="newEmpId"
							size="mini"
							query-name="newEmpName"
							:form-data="scope.row"
							@on-select="onSelectNewEmpChange($event, scope.rowIndex)"
						></remote-search-emp-input>
					</template>
				</vxe-column>
				<vxe-column title="上岗时间" align="left" field="beginTime" :width="210">
					<template slot-scope="scope">
						<jk-date-picker
							v-model="scope.row.beginTime"
							type="datetime"
							size="mini"
							value-format="yyyy-MM-dd HH:mm:ss"
							@change="onBeginTimeChange($event, scope)"
						></jk-date-picker>
					</template>
				</vxe-column>
				<vxe-column title="下岗时间" align="left" field="endTime" :width="210">
					<template slot-scope="scope">
						<jk-date-picker
							v-model="scope.row.endTime"
							:disabled="!scope.row.beginTime"
							type="datetime"
							size="mini"
							value-format="yyyy-MM-dd HH:mm:ss"
							@change="onEndChange($event, scope)"
						></jk-date-picker>
					</template>
				</vxe-column>
				<vxe-column title="替岗机台" align="left" field="replacePostMachineList" :min-width="160">
					<template slot-scope="scope">
						<div class="flex-start-center-wrap">
							<div
								v-for="(machineItem, machineIndex) in scope.row.replacePostMachineList || []"
								:key="`t-${machineItem.machineId}`"
								style="width: calc(100% / 4);padding: 2px;box-sizing: border-box;"
							>
								<el-tag :closable="true" size="mini" class="width-100-percent flex-between-center" @close="onDeleteMachineBtn(scope.rowIndex, machineIndex)">{{ machineItem.machineName }}</el-tag>
							</div>
							<el-popover title="选择机台" trigger="click" style="width: calc(100% / 4);padding: 2px;box-sizing: border-box;flex-shrink: 0;">
								<div class="flex-start-center-wrap width-100-percent">
									<div
										v-for="(machineItem) in machineList || []"
										:key="`s-${machineItem.machineId}`"
										class=""
										style="width: calc(100% / 4);flex-shrink: 0;padding: 2px;box-sizing: border-box;"
									>
										<jk-button
											:type="scope.row.replacePostMachineList.map(x => x.machineId).includes(machineItem.machineId) ? 'primary' : 'default'"
											size="mini"
											class="width-100-percent flex-between-center"
											@click="onSelectMachineBtn(scope, machineItem)"
										>{{ machineItem.machineName }}</jk-button>
									</div>
								</div>
								<div slot="reference" style="cursor: pointer;">
									<el-tag size="mini" class="flex-center" type="info"><span class="el-icon-plus"></span></el-tag>
								</div>
							</el-popover>
						</div>
					</template>
				</vxe-column>
			</jk-table>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        workforceManagementScheduleReplacePostCreate,
        workforceManagementScheduleReplacePostUpdate
    } from '../../../api/schedule/empReplacePost';
    import { formatHoursMinutes, tipsBar } from '../../../utils/jk/jk-tool';
    import remoteSearchEmpInput from '../../production/order/components/remote-search-emp-input';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    export default {
        name: 'EmpReplacePost',
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            dataItem: {
                type: Object,
                default() {
                    return {
                        'id': null, // 替岗记录ID
                        'belongDate': '',
                        'scheduleId': 1,
                        'scheduleShiftId': 1,
                        'scheduleShiftName': 1,
                        'scheduleGroupId': 1,
                        'scheduleGroupName': 1,
                        'scheduleShiftBeginTime': '',
                        'scheduleShiftEndTime': '',
                        'beginTime': '',
                        'endTime': '',
                        'scheduleEmpId': 1,
                        'scheduleEmpName': 1,
                        'scheduleEmpPostList': []
                    };
                }
            }
        },
        components: {
            remoteSearchEmpInput
        },
        mixins: [calHeight],
        data() {
            return {
                tableData: [],
                checkArr: [],
                machineList: [],
                causeList: [],
                scheduleNewEmpMachineList: [],
                scheduleOldEmpMachineList: [],
                schedulePostList: [],
                scheduleEmpList: [],
                scheduleGroupList: [],
                saveBtnLoading: false,
                workshopList: [],
                showDialog: false,
                showLoading: false,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    'workshopId': 0,
                    'workshopName': '',
                    'belongDate': '',
                    'scheduleId': 0,
                    'scheduleShiftId': 0,
                    'scheduleShiftName': 0,
                    'scheduleShiftBeginTime': '',
                    'scheduleShiftEndTime': '',
                    'scheduleGroupId': 0,
                    'scheduleGroupName': 0,
                    'scheduleEmpId': 0,
                    'scheduleEmpName': 0,
                    'schedulePostId': 0,
                    'workingHours': 0,

                    'replaceTime': '',
                    'scheduleEmpExceptionalCaseId': 0,
                    'scheduleEmpExceptionalCaseName': '',

                    'beginTime': '',
                    'endTime': '',
                    'processCode': '',
                    'processId': 0,
                    'processName': '',
                    'remark': '',
                    'postMachineList': [],
                    'replaceEmpList': []
                },
                rules: {
                    postId: [{ required: true, trigger: 'change' }],
                    scheduleEmpExceptionalCaseId: [{ required: true, trigger: 'change' }]
                },
                selectNewMachineData: [],
                selectOldMachineData: [],
                defaultRowData: {
                    'newEmpId': 0,
                    'newEmpName': '',
                    'beginTime': '',
                    'endTime': '',
                    'replaceHours': 0,
                    'replacePostMachineList': []
                }
            };
        },
        methods: {
            onSelectMachineBtn(scope, machineItem) {
                let arr = scope.row.replacePostMachineList ? JSON.parse(JSON.stringify(scope.row.replacePostMachineList)) : [];
                if (arr.map(x => x.machineId).includes(machineItem.machineId)) {
                    arr = arr.filter(x => x.machineId !== machineItem.machineId);
                } else {
                    arr.push({
                        machineId: machineItem.machineId,
                        machineCode: machineItem.machineCode,
                        machineName: machineItem.machineName
                    });
                }
                this.$set(this.ruleForm.replaceEmpList[scope.rowIndex], 'replacePostMachineList', arr);
            },
            onBeginTimeChange(e, { row, rowIndex }) {
                if (e) {
                    if (Date.parse(e) >= Date.parse(this.ruleForm.startDateTime) && Date.parse(e) < Date.parse(this.ruleForm.endDateTime)) {
                        if (row.endTime && Date.parse(e) < Date.parse(row.endTime)) {

                        } else {
                            tipsBar(this, 'custom', 'warning', '上岗时间不能大于下岗开始时间!');
                        }
                    } else {
                        tipsBar(this, 'custom', 'warning', '上岗时间不能大于班次开始时间!');
                    }
                } else {
                    this.$set(this.ruleForm.replaceEmpList[rowIndex], 'endTime', '');
                }
            },
            onEndChange(e, { row, rowIndex }) {
                if (e) {
                    if (Date.parse(e) > Date.parse(row.beginTime) && Date.parse(e) <= Date.parse(this.ruleForm.endDateTime)) {

                    } else {
                        tipsBar(this, 'custom', 'warning', '下岗时间不能大于上岗或班次结束时间!');
                    }
                } else {
                    this.$set(this.ruleForm.replaceEmpList[rowIndex], 'beginTime', '');
                }
            },
            getMachines() {
                let arr = this.machineList ? JSON.parse(JSON.stringify(this.machineList)).filter(x => this.checkArr.includes(x.machineId)) : [];
                arr = arr.map(x => {
                    return {
                        machineId: x.machineId,
                        machineCode: x.machineCode,
                        machineName: x.machineName
                    };
                });
                return arr;
            },
            onCheckboxChange() {
                this.ruleForm.replaceEmpList.forEach(x => {
                    this.$set(x, 'replacePostMachineList', this.getMachines());
                });
            },
            getMachineByPostId() {
                const item = this.ruleForm.scheduleEmpPostList.find(x => x.postId === this.ruleForm.postId) ? this.ruleForm.scheduleEmpPostList.find(x => x.postId === this.ruleForm.postId) : {};
                this.machineList = item.scheduleEmpMachineList;
                this.checkArr = this.machineList.map(x => x.machineId);
            },
            transformFatherData() {
                const resData = this.dataItem ? JSON.parse(JSON.stringify(this.dataItem)) : {};
                resData.scheduleEmpExceptionalCaseId = null;
                resData.scheduleEmpExceptionalCaseName = '';
                resData.remark = '';
                resData.replaceEmpList = [];
                const postItem = resData.scheduleEmpPostList && resData.scheduleEmpPostList.length ? resData.scheduleEmpPostList[0] : {};
                resData.postId = postItem.postId;
                resData.postName = postItem.postName;
                this.ruleForm = resData;
                this.getMachineByPostId();
            },
            onAddBtn(index) {
                const cpData = JSON.parse(JSON.stringify(this.defaultRowData));
                cpData.replacePostMachineList = this.getMachines();

                cpData.beginTime = this.ruleForm.startDateTime;
                cpData.endTime = this.ruleForm.endDateTime;
                if (index || index === 0) {
                    this.ruleForm.replaceEmpList.splice(index + 1, 0, cpData);
                } else {
                    this.ruleForm.replaceEmpList.push(cpData);
                }
            },
            onDeleteMachineBtn(empIndex, machineIndex) {
                this.ruleForm.replaceEmpList[empIndex].replacePostMachineList.splice(machineIndex, 1);
            },
            onDeleteBtn(index) {
                this.ruleForm.replaceEmpList.splice(index, 1);
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                delete params.scheduleEmpPostList;
                params.scheduleEmpExceptionalCaseName = this.causeList.find(x => x.id === params.scheduleEmpExceptionalCaseId) ? this.causeList.find(x => x.id === params.scheduleEmpExceptionalCaseId).name : '';
                return params;
            },
            onSelectNewEmpChange(e, index) {
                this.$set(this.ruleForm.replaceEmpList[index], 'newEmpId', e.id);
                this.$set(this.ruleForm.replaceEmpList[index], 'newEmpName', e.name);
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid && this.ruleForm.replaceEmpList && this.ruleForm.replaceEmpList.length) {
                        let isValidatorOk = true;
                        this.ruleForm.replaceEmpList.forEach(x => {
                            if (Date.parse(x.beginTime) >= Date.parse(x.endTime) || Date.parse(x.beginTime) < Date.parse(this.ruleForm.startDateTime) || Date.parse(x.endTime) > Date.parse(this.ruleForm.endDateTime)) {
                                isValidatorOk = false;
                            }
                            if (!x.newEmpId) {
                                isValidatorOk = false;
                            }
                        });
                        if (isValidatorOk) {
                            this.createAndUpdateRequest();
                        } else {
                            this.$tipsBar(this, 'custom', 'warning', '请将新值班人员或上、下岗时间填写准确!');
                        }
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = this.dataItem.id ? workforceManagementScheduleReplacePostUpdate : workforceManagementScheduleReplacePostCreate;
                this.saveBtnLoading = true;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getCauseListRequest() {
                return systemBusinessDictPage({
                    categoryCode: 'REMOVE_EMP_CAUSE',
                    pageSize: 100,
                    pageNo: 1
                }).then(res => {
                    if (res.data.status === 200) {
                        this.causeList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                // this.showLoading = true;
                this.transformFatherData();
                await this.getCauseListRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
.table-title {
    font-size: 14px;
}
.arrow-operation-bar {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
</style>
